package com.info.zhiduoduo.pay.sdk.dayspaysdk.core.client.http.proxy;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 * 
 * @author luoyunqiu
 * @time 2016-09-12 20:54
 */
public class HttpProxyClient {
	
	private static Map<String, HttpProxyRouter> routers = Collections.synchronizedMap(new HashMap<String, HttpProxyRouter>());
	
	private static HttpProxyRouter getRouter(String clientName){
		synchronized(routers){
			HttpProxyRouter router = routers.get(clientName);
			if(null == router){
				router = new HttpProxyRouter();
				routers.put(clientName, router);
			} else {
				router.setLastUserTime(System.currentTimeMillis());
			}
			clearUnUseRouter();
			return router;
		}
	}
	private static void clearUnUseRouter(){
		Iterator<Map.Entry<String, HttpProxyRouter>> iterator = routers.entrySet().iterator();
		long max = 1000L * 60 * 60;
		while(iterator.hasNext()){
			Map.Entry<String, HttpProxyRouter> entity = iterator.next();
			long dis = System.currentTimeMillis() - entity.getValue().getLastUserTime();
			if(dis > max){
				iterator.remove();
			}
		}
	}
	/**
	 * 
	 * @param addresses ��ַ��ʽ��
	 *  �����ַ1;�����ַ2;......|Ŀ���ַ1;Ŀ���ַ2......|Ȩ��1;Ȩ��2;Ȩ��3;Ȩ��4......|���ӳ�ʱ(��λ����)|��ȡ�ȴ���ʱ(��λ����)|���ȴ���ʱ����(���������ͣN������)|����ȴ���ʱʱ������|��ͣ����
	 *  Ȩ��1=�����ַ1--Ŀ���ַ1
		Ȩ��2=�����ַ1--Ŀ���ַ2
		Ȩ��3=�����ַ2--Ŀ���ַ1
		Ȩ��4=�����ַ2--Ŀ���ַ2
		���������Ȩ����գ���Ĭ�϶�Ϊ1:1:1:1......
	 * @param data ����
	 * @param headers ����Ҫ���http����ͷ
	 * @return
	 */
	public static HttpResult httpPost(String addresses, byte[] data, Map<String, String> headers){
		return getRouter(addresses).httpPost(addresses, data, headers);
	}
	public static HttpResult httpPost(String method, String addresses, String extraparams, byte[] data, Map<String, String> headers){
		return getRouter(addresses).httpPost(addresses, extraparams, data, headers);
	}
	
	public static HttpResult httpGet(String addresses, String data, Map<String, String> headers){
		return getRouter(addresses).httpGet(addresses, data, headers);
	}
}